package com.dao.c.backend.service.impl;

import com.dao.c.backend.common.CommonResult;
import com.dao.c.backend.common.MessageCode;
import com.dao.c.backend.common.StatusCode;
import com.dao.c.backend.entity.User;
import com.dao.c.backend.dao.UserMapper;
import com.dao.c.backend.entity.WeChatSessionModel;
import com.dao.c.backend.service.IUserService;
import com.dao.c.backend.utils.AesUtil;
import com.dao.c.backend.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.apache.commons.codec.digest.DigestUtils;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张幸晔
 * @since 2025-02-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    private final AesUtil aesUtil;

    @Autowired // 自动注入 AesUtil
    public UserServiceImpl(AesUtil aesUtil) {
        this.aesUtil = aesUtil;
    }

    @Override
    public CommonResult login(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        System.out.println(user);
        lambdaQueryWrapper.select(User.class,lambdaUser ->!lambdaUser.getColumn().equals("openid_hash")).eq(User::getUsername,user.getUsername());
        User isUser = userMapper.selectOne(lambdaQueryWrapper);
        System.out.println(isUser);
        return commonLogin(isUser,null,user.getPassword());
    }

    @Override
    public CommonResult sign(User user) {
        return null;
    }




    private CommonResult commonLogin(User user,WeChatSessionModel weChatSessionModel,String password){
        if (user == null){
            //需要注册，将openid返回，让用户用此去获取手机号
            return new CommonResult<>(StatusCode.NOT_REGISTER,"用户未注册，请前往注册",weChatSessionModel);
        } else if (user.getStatus() == 0) {
            return new CommonResult<>(StatusCode.ERROR,"用户状态异常，请联系管理员",null);
        } else if (user.getStatus() == -1){
            Map<String,Object> idMap = new HashMap<>();
            idMap.put("id",user.getId());
            return new CommonResult<>(StatusCode.LOGOUT,"用户已注销",idMap);
        }
        //检测到用户，检验密码是否正确
        if (password != null){
            if (!password.equals(user.getPassword())){
                return new CommonResult<>(StatusCode.ERROR,"用户密码账号不匹配",null);
            }
        }
        //检索到用户且用户成功登录，生成token并将user内容和token返回
        Map<String,Object> map = new HashMap<>();
        Map<String,String> payload = new HashMap<>();
        if (weChatSessionModel != null){
            payload.put("openid",user.getOpenid());
        }else {
            payload.put("username",user.getUsername());
        }
        //对用户的手机号和邮箱做掩码操作
        phoneAndEmailMask(user);
        user.setOpenid(null);
        user.setPassword(null);
        map.put("user",user);
        String token = JWTUtil.buildToken(payload);
        map.put("token",token);
        return new CommonResult<>(StatusCode.SUCCESS,"登录成功",map);
    }



    private void phoneAndEmailMask(User user){
        if (user.getPhone() != null && !"".equals(user.getPhone())){
            try {
                String phone = aesUtil.decrypt(user.getPhone());
                user.setPhone(phone.substring(0, 3) + "****" + phone.substring(7));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (user.getEmail()!=null && !"".equals(user.getEmail())){
            try {
                String email = aesUtil.decrypt(user.getEmail());
                String[] parts = email.split("@");
                String localPart = parts[0];
                user.setEmail (localPart.length() > 4
                        ? localPart.substring(0, 2) + "****" + localPart.substring(localPart.length() - 2)
                        : "****"
                        + "@" + parts[1]);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
